package cn.qingyun.gis.modules.init.utils;

import cn.qingyun.gis.modules.init.system.entity.SysDict;
import cn.qingyun.gis.modules.init.system.entity.SysDictItem;
import cn.qingyun.gis.modules.init.system.service.ISysDictItemService;
import cn.qingyun.gis.modules.init.system.service.ISysDictService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@Data
public class DictUtil {

    private static ISysDictItemService sysDictItemService;
    private static ISysDictService sysDictService;

    /**
     * 获取字典项值
     *
     * @param dictCode 字典编码
     * @return
     */
    public static List<SysDictItem> getItemByDictCode(String dictCode) {
        // 根据dictCode查询字典
        Map<String, Object> queryDictMap = new HashMap<>();
        queryDictMap.put("dict_code", dictCode);
        List<SysDict> dictList = sysDictService.listByMap(queryDictMap);
        if (dictList.isEmpty()) {
            return new ArrayList();
        }
        // 根据dictId查询字典项
        Map<String, Object> queryDictItemMap = new HashMap<>();
        queryDictItemMap.put("dict_id", dictList.get(0).getId());
        return sysDictItemService.listByMap(queryDictItemMap);
    }

    /**
     * 获取字典项值
     *
     * @param dictCode 字典编码
     * @return
     */
    public static String getDictItemValueByName(String dictCode, String dictName) {
        String itemValue = "";
        // 根据dictCode查询字典
        List<SysDictItem> itemByDictCodeList = getItemByDictCode(dictCode);
        for(SysDictItem dictItem : itemByDictCodeList){
            if (dictName.equals(dictItem.getItemText())){
                itemValue = dictItem.getItemValue();
                break;
            }
        }
        return itemValue;
    }

    /**
     * 获取字典项值
     *
     * @param dictCode 字典编码
     * @return
     */
    public static String getDescValueByName(String dictCode, String dictName) {
        String desc = "";
        // 根据dictCode查询字典
        List<SysDictItem> itemByDictCodeList = getItemByDictCode(dictCode);
        for(SysDictItem dictItem : itemByDictCodeList){
            if (dictName.equals(dictItem.getItemText())){
                desc = dictItem.getDescription();
                break;
            }
        }
        return desc;
    }

    @Autowired
    public void setDictItemService(ISysDictItemService sysDictItemService) {
        DictUtil.sysDictItemService = sysDictItemService;
    }

    @Autowired
    public void setDictService(ISysDictService sysDictService) {
        DictUtil.sysDictService = sysDictService;
    }
}
